package com.pubinfo.passbook.data.service.impl;

import api.VoucherFileUtil;
import com.alibaba.fastjson.JSONObject;
import com.pubinfo.passbook.common.entity.TFileInfo;
import com.pubinfo.passbook.common.exception.ServiceException;
import com.pubinfo.passbook.common.mapper.TFileInfoMapper;
import com.pubinfo.passbook.common.model.dto.file.FileInfoParam;
import com.pubinfo.passbook.data.service.VoucherFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class VoucherFileServiceImpl implements VoucherFileService
{

    @Autowired
    TFileInfoMapper tFileInfoMapper;

    @Override
    public JSONObject invoiceOdf2Json(String fileId) throws Exception {

        FileInfoParam fileInfoParam=tFileInfoMapper.selectFileInfoParam(fileId);

        if(!fileInfoParam.getContentType().equals("application/ofd"))
        {
            throw new ServiceException("文件非版式文件");
        }

        String fileName=fileInfoParam.getName().replaceAll("\\.ofd","");
        String filePath=fileInfoParam.getPath().replaceAll(fileName+"\\.ofd","");
        String invoiceType=fileInfoParam.getFplx();
        String type=null;

        if(invoiceType.equals("ZZS_DZFP")) {
            //电子普票
            type="inv_ord_issuer";
        }
        else if(invoiceType.equals("ZZS_DZZP")) {
            //电子专票
            type="inv_spcl_issuer";
        }
        else if(invoiceType.equals("DZ_TXFFP")) {
            //通行费发票
            type="inv_tlf_issuer";
        }
        else {
            //其他暂时没版式文件同步
            throw new ServiceException("暂不支持此类发票解析");
        }

        return ofd2Json(filePath,fileName,type);
    }

    @Override
    public JSONObject ofd2Json(String filePath,String fileName, String type) throws Exception {
        //将odf转换成xml格式
        VoucherFileUtil.extractXBRLFromOFD(filePath+fileName+".ofd",filePath+fileName+".xbrl");
        //读取xml之后转换成json
        BufferedReader br = new BufferedReader(new FileReader(filePath+fileName+".xbrl"));//构造一个BufferedReader类来读取文件
        String s = null;
        int sum=0;
        StringBuffer stringBuffer=new StringBuffer();
        while((s = br.readLine())!=null){//使用readLine方法，一次读一行
            stringBuffer.append(s);
        }
        br.close();
        //删除xbrl文件
        File file = new File(filePath+fileName+".xbrl");
        file.delete();
        return VoucherFileUtil.xbrl2Json(stringBuffer.toString(),type);
    }
}
